﻿using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;
using IdentityServerManagement.Clients;

namespace IdentityServerManagement
{
    public class AllowedCorsOriginsCacheItemInvalidator : 
        ILocalEventHandler<EntityChangedEventData<Client>>,
        ILocalEventHandler<EntityChangedEventData<ClientCorsOrigin>>,
        ITransientDependency
    {
        protected IIdentityServerCacheContext IdentityServerCacheContext { get; }

        public AllowedCorsOriginsCacheItemInvalidator(IIdentityServerCacheContext identityServerCacheContext)
        {
            IdentityServerCacheContext = identityServerCacheContext;
        }
        
        public virtual async Task HandleEventAsync(EntityChangedEventData<Client> eventData)
        {
            await IdentityServerCacheContext.AllowedCorsOrigins.RemoveAsync(AllowedCorsOriginsCacheItem.AllOrigins);
        }

        public virtual async Task HandleEventAsync(EntityChangedEventData<ClientCorsOrigin> eventData)
        {
            await IdentityServerCacheContext.AllowedCorsOrigins.RemoveAsync(AllowedCorsOriginsCacheItem.AllOrigins);
        }
    }
}